import datetime
from django.core.management.base import BaseCommand
from django.db import transaction
from catalog.models import Author, Book, BookInstance, Genre, Language

class Command(BaseCommand):
    help = 'Imports data for Patrick Rothfuss and his books as shown in the screenshot.'

    @transaction.atomic
    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Starting data import for Patrick Rothfuss...'))

        # 1. Get or create Genre
        genre_fantasy, created = Genre.objects.get_or_create(name='Fantasy')
        if created:
            self.stdout.write(self.style.SUCCESS(f'Genre "{genre_fantasy.name}" created.'))
        else:
            self.stdout.write(f'Genre "{genre_fantasy.name}" already exists.')

        # 2. Get or create Language
        lang_english, created = Language.objects.get_or_create(name='English')
        if created:
            self.stdout.write(self.style.SUCCESS(f'Language "{lang_english.name}" created.'))
        else:
            self.stdout.write(f'Language "{lang_english.name}" already exists.')

        # 3. Create or update Author: Patrick Rothfuss
        # Using the birth date from the screenshot: June 6, 2073
        author_dob = datetime.date(2073, 6, 6)
        author_rothfuss, created = Author.objects.get_or_create(
            first_name='Patrick',
            last_name='Rothfuss',
            defaults={'date_of_birth': author_dob}
        )
        if created:
            self.stdout.write(self.style.SUCCESS(f'Author "{author_rothfuss}" created with DOB {author_dob}.'))
        else:
            if author_rothfuss.date_of_birth != author_dob:
                author_rothfuss.date_of_birth = author_dob
                author_rothfuss.save()
                self.stdout.write(f'Author "{author_rothfuss}" DOB updated to {author_dob}.')
            else:
                self.stdout.write(f'Author "{author_rothfuss}" (DOB: {author_rothfuss.date_of_birth}) already exists.')

        # 4. Book 1: The Name of the Wind
        book1_title = 'The Name of the Wind (The Kingkiller Chronicle, #1)'
        book1_summary = "Told in Kvothe's own voice, this is the tale of the magically gifted young man who grows to be the most notorious wizard his world has ever seen."
        book1_isbn = '978-0-7564-0407-9' # Actual ISBN, not visible in screenshot

        book1, created = Book.objects.get_or_create(
            isbn=book1_isbn,
            defaults={
                'title': book1_title,
                'author': author_rothfuss,
                'summary': book1_summary,
                'language': lang_english,
            }
        )
        if created:
            book1.genre.add(genre_fantasy)
            self.stdout.write(self.style.SUCCESS(f'Book "{book1.title}" created.'))
        else:
            # Ensure fields are correct if it already exists
            book1.title = book1_title
            book1.author = author_rothfuss
            book1.summary = book1_summary
            book1.language = lang_english
            book1.save() # Save other fields before ManyToMany
            if not book1.genre.filter(pk=genre_fantasy.pk).exists():
                book1.genre.add(genre_fantasy)
            self.stdout.write(f'Book "{book1.title}" already exists, ensured data is up-to-date.')

        # 5. Book 2: The Wise Man's Fear
        book2_title = "The Wise Man's Fear (The Kingkiller Chronicle, #2)"
        book2_summary = "My name is Kvothe. I have stolen princesses back from sleeping barrow kings. I burned down the town of Trehon. I have spent the night with Felurian and left with both my sanity and my life. I was expelled from the University at a younger age"
        book2_isbn = '978-0-7564-0474-1' # Actual ISBN, not visible in screenshot

        book2, created = Book.objects.get_or_create(
            isbn=book2_isbn,
            defaults={
                'title': book2_title,
                'author': author_rothfuss,
                'summary': book2_summary,
                'language': lang_english,
            }
        )
        if created:
            book2.genre.add(genre_fantasy)
            self.stdout.write(self.style.SUCCESS(f'Book "{book2.title}" created.'))
        else:
            book2.title = book2_title
            book2.author = author_rothfuss
            book2.summary = book2_summary
            book2.language = lang_english
            book2.save() # Save other fields before ManyToMany
            if not book2.genre.filter(pk=genre_fantasy.pk).exists():
                book2.genre.add(genre_fantasy)
            self.stdout.write(f'Book "{book2.title}" already exists, ensured data is up-to-date.')

        # 6. Add BookInstances
        # For Book 1 (target 3 copies)
        book1_copies_target = 3
        book1_existing_copies = BookInstance.objects.filter(book=book1).count()
        for _ in range(book1_copies_target - book1_existing_copies):
            BookInstance.objects.create(book=book1, imprint='Default Imprint (Imported)', status='a') # 'a' for Available
        self.stdout.write(f'Ensured {book1_copies_target} copies for "{book1.title}". Created {max(0, book1_copies_target - book1_existing_copies)} new copies.')

        # For Book 2 (target 2 copies)
        book2_copies_target = 2
        book2_existing_copies = BookInstance.objects.filter(book=book2).count()
        for _ in range(book2_copies_target - book2_existing_copies):
            BookInstance.objects.create(book=book2, imprint='Default Imprint (Imported)', status='a')
        self.stdout.write(f'Ensured {book2_copies_target} copies for "{book2.title}". Created {max(0, book2_copies_target - book2_existing_copies)} new copies.')

        self.stdout.write(self.style.SUCCESS('Data import for Patrick Rothfuss completed successfully!'))
